package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.*;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.ExcelUtil;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.io.File;
import java.io.FileInputStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private BlogMapper blogMapper;
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<PublicDataDTO> getTwoDataTest(PublicRequestDTO publicRequestDTO) {
        List<PublicDataDTO> userNumList = blogMapper.getTwoDatauserNum(publicRequestDTO);
        List<PublicDataDTO> shopNumList = blogMapper.getTwoDataShopNum(publicRequestDTO);
        Map<String, Integer> collect = shopNumList.stream().collect(Collectors.toMap(PublicDataDTO::getDate, PublicDataDTO::getShopNum));
        for (PublicDataDTO publicDataDTO : userNumList) {
            Integer shopNum = collect.get(publicDataDTO.getDate());
            publicDataDTO.setShopNum(shopNum);
        }
        return userNumList;
    }

    @Override
    public TwoDataTestResponseDTO getTwoDataTestResponseData(PublicRequestDTO publicRequestDTO) {
        TwoDataTestResponseDTO twoDataTestResponseDTO = new TwoDataTestResponseDTO();
        Integer userNum = blogMapper.getTwoDataTestUserNumData(publicRequestDTO);
        Integer shopNum = blogMapper.getTwoDataTestShopNumData(publicRequestDTO);
        twoDataTestResponseDTO.setUserNum(userNum);
        twoDataTestResponseDTO.setShopNum(shopNum);
        return twoDataTestResponseDTO;
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            isBlogLiked(blog);
            queryBlogByUser(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询top5的点赞用户  zrange key 0 4
        String key = "blog:liked:" + id;
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (range == null || range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.解析出来用户id
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String idsString = StrUtil.join(",", ids);
        List<UserDTO> userDTOList = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idsString + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //3.根据用户id查询用户
        return Result.ok(userDTOList);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }
        queryBlogByUser(blog);
        //查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            //用户未登录，无需查询是否点赞
            return;
        }
        Long userId = UserHolder.getUser().getId();
        //判断当前登录用户是否已经点赞了
        String key = "blog:liked:"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score !=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //获取登录用户
        Long userId = UserHolder.getUser().getId();
        //判断当前登录用户是否已经点赞了
        String key = "blog:liked:"+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null){
            //如果未点赞可以点赞，数据库点赞数+1,保存用户到redis的set集合  zadd key value score
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else{
            //如果已经点赞，取消点赞，数据库点赞数-1,吧用户从redis中移除
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }

        }
        return Result.ok();
    }

    private void queryBlogByUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public void readExcel() throws Exception {
        //fileName可以定位为 String fileName =“你的路径” ，下面这样写是为了上传至服务器,如果感兴趣可以看我的服务器上传讲解
        String fileName = "C:\\Users\\yangkaile\\Desktop\\test.xlsx";
        //fileName = filePath + File.separator + fileName;
        //根据路径生成 FileInputStream字节流
        FileInputStream inputStream = new FileInputStream(new File(fileName));
        //通过ExcelUtils工具将Excel数据存入到list中，工具代码下面细讲,这一步读取Excel已经完成了，如果不想进行插入数据库操作，可以直接拿着list用啦。
        List<List<Object>> list = ExcelUtil.getListByExcel(inputStream,fileName);


        //以上读取Excel完成，list就是数据,下面进行插入数据库的操作
        //定义Excel第一行的属性
        List<Object> firstRows = null;
        //获取第一行属性 放入firstRows中。
        if(list != null && list.size() > 0){
            firstRows = list.get(0);
        }
        //遍历除第一行以外的Excel表格中的值
        for (int i = 1; i < list.size(); i++) {
            //rows是某一行，i = 1 为第二行，	i = 2 为第三行
            List<Object> rows = list.get(i);
            //数据库数据的实体类
            Blog questionBank =new Blog();
            //遍历这一行所有的值
            for (int j = 0; j < rows.size(); j++){
                //某一行的某一列 j为列的坐标
                String cellVal = String.valueOf(rows.get(j));
                //对实体类进行赋值,使用setFieldValueByFieldName方法，下面详细讲代码
                ExcelUtil.setFieldValueByFieldName(questionBank, firstRows.get(j).toString().trim(),cellVal);
            }
            blogMapper.insert(questionBank);
        }
    }
}
